﻿using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Common;
using ZoneLineNew.Models.StationConfig;
using ZoneLineNew.Models.StationResult.QOPStation;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Print;

namespace ZoneLineNew.Services.Station.COPStation
{
    /// <summary>
    /// 合件压装工位
    /// </summary>
    /// <remarks>
    /// <para>StationCode：OP610</para>
    /// <para>IP：192.168.10.120</para>
    /// </remarks>
    public class COP610StationService : WorkStationBaseService<COP610StationResult, COP610StationConfig>
    {

        public COP610StationService(
            IDbOperate<IFreeSqlMainContext> mainDbOperate, 
            IEventAggregator eventAggregator, 
            PrinterLabelService printerService
            )
            : base(mainDbOperate, eventAggregator, printerService) {

            _ = Task.Factory.StartNew(() => {
                if (IsConnected)
                {
                    base.WriteData("DB1001.14", (short)Cache.CurWorkProduct.WorkDirection);
                    base.WriteData("DB1001.2168", Cache.CurWorkProduct.ProductName);
                }
            });
        }

        public override void DealWithSignal(string signalName)
        {
            if (signalName == nameof(StartUploadCode))
            {
                if (StartUploadCode == false)
                {
                    LogWithUi($"在{CurrentStationName}收到上传条码命令变为false", StationRecordData.AbsScanCode);
                    WriteData(StationConfig.EndUploadCodeAddr, 0, StationRecordData.AbsScanCode);
                    WriteData(StationConfig.AllowWorkAddr, 0, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}复位工作控制指令和复位上传条码完成指令", StationRecordData.AbsScanCode);
                }
                else
                {
                    LogWithUi($"在{CurrentStationName}收到上传条码信息命令", StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}工位结论验证,条码信息是{StationRecordData.AbsScanCode}", StationRecordData.AbsScanCode);
                    var validataRlt = Validata(CurrentStationName, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}工位的验证结果是{validataRlt}", StationRecordData.AbsScanCode);
                    var writeRlt = WriteWorkActionToPlc(StationConfig.AllowWorkAddr, validataRlt, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt}", StationRecordData.AbsScanCode);
                }
                return;
            }

            if (signalName == nameof(StartUploadData))
            {
                if (StartUploadData)
                {
                    //todo 上传数据 这时候将数据记录到数据库中
                    LogWithUi($"在{CurrentStationName}收到上传记录数据命令", StationRecordData.AbsScanCode);
                    var rlt = RecordData();
                    WriteData(StationConfig.EndUploadDataAddr, (short)rlt, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}数据记录,rlt={rlt}", StationRecordData.AbsScanCode);
                }
                else
                {
                    LogWithUi($"在{CurrentStationName}收到上传记录数据命令变为false", StationRecordData.AbsScanCode);

                    WriteData(StationConfig.EndUploadDataAddr, 0, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}数据记录,clear", StationRecordData.AbsScanCode);
                }
            }
        }

        public override void DealData(byte[] content)
        {

            StationRecordData.AbsScanCode = GetPlcString(content, 12);
            StationRecordData.PartType = GetPlcString(content, 34);
            //StationRecordData.Result = _client.ByteTransform.TransInt16(content, 1000).ToString().Equals("1") ? "OK" : "NG";
            StationRecordData.CycleTime = _client.ByteTransform.TransSingle(content, 82);

        }


        public override void DealWithCommonData(byte[] content)
        {

            Heart = _client.ByteTransform.TransBool(content, 18 * 8);
            StartUploadCode = _client.ByteTransform.TransBool(content, 80 * 8);
            StartUploadData = _client.ByteTransform.TransBool(content, 80 * 8 + 1);

            HeartToPlc = _client.ByteTransform.TransBool(content, 80 * 8 + 3);
            EndUpLoadCode = _client.ByteTransform.TransBool(content, 80 * 8 + 4);
            EndUpLoadData = _client.ByteTransform.TransBool(content, 80 * 8 + 5);
            AllowWork = _client.ByteTransform.TransInt16(content, 20);

        }

        public override int RecordData()
        {

            var result = new COP610StationResult()
            {
                StationCode = base.StationConfig.StationCode,
                AbsScanCode = StationRecordData.AbsScanCode,
                //ArmScanCode = StationRecordData.ArmScanCode,
                //BoltScanCode = StationRecordData.BoltScanCode,
                CycleTime = StationRecordData.CycleTime,
                //NutScanCode = StationRecordData.NutScanCode,
                PartType = StationRecordData.PartType,
                Result = StationRecordData.Result,
                //TightenAngle = StationRecordData.TightenAngle,
                //TightenPosition = StationRecordData.TightenPosition,
                //TightenTorque = StationRecordData.TightenTorque
            };
            var writeRlt = false;
            if (_mainDbOperate.CheckExist<COP610StationResult>(p => p.AbsScanCode == result.AbsScanCode))
            {
                var beforeRlt = _mainDbOperate.GetModel<COP610StationResult>(p => p.AbsScanCode == result.AbsScanCode);
                result.Id = beforeRlt.Id;
                writeRlt = _mainDbOperate.UpdateModelSuper<COP610StationResult>(p => p.AbsScanCode == result.AbsScanCode, result);
            }
            else
            {
                writeRlt = _mainDbOperate.AddModel(result);
            }
            return writeRlt ? 1 : 2;
        }
    }

}
